#include "input_thread.h"

static struct input_thread *input_thread_t = NULL;

void * read_from_socket() 
{
	int numbytes;
	char buf[BUF_SIZE];
	int sockfd;
	struct list_node *node;
	struct plugin *plugin;

	sockfd = input_thread_t->IRC_core_t->socket_t->sockfd;

	while ( input_thread_t->is_running ) {
	
		if ( ( numbytes = recv(sockfd, buf, BUF_SIZE-1, 0) ) == -1 ) 	{
        perror("recv");   
  	}
		if ( numbytes == 0 ) { /* Connection closed by host */
			printf("Connection closed by host... signal to IRC_core... \n");		
			host_disconnected_IRC_core();	
			break;
		}

  	buf[numbytes] = '\0';

		if ( numbytes > 0 ) { 

			node = input_thread_t->plugin_list->head;
			while ( node != NULL ) {
				plugin = (struct plugin*)node->data;
				plugin->handle_msg( buf );
				node = node->next;
			}
		}

	} /* while */

	input_thread_t->is_running = 0;

	pthread_exit( NULL );
}

struct input_thread * new_input_thread( struct IRC_core *IRC_core_t )
{
	int res;

	input_thread_t = (struct input_thread*) malloc( sizeof( struct input_thread ) );
	if ( input_thread_t == NULL ) {
		fprintf( stderr, "Input thread allocation failed, out of memory. \n" );
		return NULL;	
	}
	input_thread_t->IRC_core_t = IRC_core_t;

	if ( ( res = pthread_create( &input_thread_t->thread, NULL, read_from_socket, NULL) ) ) {
		fprintf(stderr, "Input thread creation failed: %d\n", res);
		return NULL;
	}

	input_thread_t->is_running = 1;

	return input_thread_t;
}

void delete_input_thread() 
{
	if ( input_thread_t ) 
		free( input_thread_t );
}
